package com.tedu.egmvc.controller;

import com.tedu.egmvc.mapper.UserMapper;

import com.tedu.egmvc.pojo.dto.UserArticleDTO;
import com.tedu.egmvc.pojo.dto.UserLoginDTO;
import com.tedu.egmvc.pojo.entity.Artical;
import com.tedu.egmvc.pojo.vo.UserVO;
import com.tedu.egmvc.result.JsonResult;
import com.tedu.egmvc.result.Status;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import javax.validation.constraints.Size;

@Slf4j
@RestController
@RequestMapping("/v1/users")
@Api(tags = "用户模块")
@Validated
public class UserController {
    @Autowired
    private UserMapper UserMapper;

    @ApiOperation(value = "用户登录")
    @PostMapping("/login")
    public JsonResult login(UserLoginDTO UserLoginDTO, HttpSession session){
        UserVO userVO = UserMapper.selectUser(UserLoginDTO.getUsername(),UserLoginDTO.getPassword());
        if(userVO != null){
            session.setAttribute("user",userVO);
            return JsonResult.success();
        }
       return new JsonResult(Status.USERNAME_PASSWORD_ERROR);
    }

    @ApiOperation(value = "发布文章")
    @PostMapping("/article")
    public JsonResult insertArtical(@RequestParam UserArticleDTO userArticleDTO,@ApiIgnore HttpSession session){
        System.out.println(userArticleDTO);;
        UserVO userVO = (UserVO) session.getAttribute("user");
        Artical artical = new Artical();
        BeanUtils.copyProperties(userArticleDTO, artical);
        artical.setUserId(userVO.getId());
        return JsonResult.success(UserMapper.insertUserArticle(artical));
    }

    @ApiOperation(value = "根据文章id查询文章")
    @PostMapping("/selectByArticleId")
    public JsonResult selectByArticleId(@Range(min = 1,max = 100) @RequestParam Integer id){
        System.out.println(id);
        return JsonResult.success(UserMapper.selectByArticleId(id));
    }

}
